# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User

class PMManager(models.Manager):
    def code_create_notification(self, from_user, to_user, obj, subject=None, message=None, commit=True):
        """Creates a PrivateMessage from from_user that notifies to_user of the creation of code/project obj.
            Returns the created PrivateMessage.
            
            from_user and to_user should each be a django.contrib.auth.models.User instance, 
            and obj should be either a codeshare.main.Code or codeshare.main.Project.
            
            Use the subject and message arguments to override the default subject and message of the created PM.
            
            Use commit=False if you want to modify the PrivateMessage before it is saved.
            """
        
        if subject is None:
            subject = """
                %s created a new %s, "%s".""" % (from_user, obj, obj.title)
        if message is None:           
            message = """
                %s created a new %s titled <a href="%s">'%s'</a>, and thought you were interested.
                """ % (from_user, obj, reverse("main:view", args=[obj.pk]), obj.title)
                
        pm = self.create(from_user=from_user, to_user=to_user, subject=subject, message=message)
        if commit:
            pm.save()
        return pm
    
    def get_user_pms(self, user, unread_only=True):
        """Returns a queryset containing all PrivateMessages which have been sent to 'user'.
            If unread_only is True (the default), only unread messages will be returned."""
        
        q = {'read':False} if unread_only else {}
        return self.get_query_set().filter(to_user=user, **q)
    
class PrivateMessage(models.Model):
    from_user = models.ForeignKey(User, related_name="sent_pms")
    to_user = models.ForeignKey(User, related_name="pm_set")
    subject = models.CharField(max_length=300)
    message = models.TextField(null=True, blank=True)
    read = models.BooleanField(default=False)
    sent = models.DateTimeField(auto_now_add=True)
    read_date = models.DateTimeField(null=True, blank=True)
    
    objects = PMManager()
    
    def __unicode__(self):
        return unicode(self.subject)
    
    class Meta:
        ordering = ('-sent', 'from_user__username')